package com.joinval.modules.sys.vo;

import com.joinval.common.utils.Constant;
import com.joinval.modules.sys.entity.SysMenuEntity;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @Auther: ronghai
 * @Date: 2020/9/2 : 14:31
 * @Desc:
 */
public class MenuTree extends SysMenuEntity{

    private List<MenuTree> children;

    public List<MenuTree> getChildren() {
        return children;
    }

    public void setChildren(List<MenuTree> children) {
        this.children = children;
    }

    public MenuTree(SysMenuEntity menu) {
        BeanUtils.copyProperties(menu,this);
        this.setChildren(new ArrayList<>());
    }

    public static List<MenuTree> buildTree(List<SysMenuEntity> menuList){
        List<MenuTree> menuTreeList = new ArrayList<>();
        for (SysMenuEntity sysMenuEntity : menuList) {
            MenuTree menuTree = new MenuTree(sysMenuEntity);
            menuTreeList.add(menuTree);
        }
        return MenuTree.setChildrenNode(menuTreeList);
    }

    private static List<MenuTree> setChildrenNode(List<MenuTree> menuTreeList){
        List<MenuTree> rt = new ArrayList<>();
        /**
         * 排序
         */
        Comparator<MenuTree> menuTreeComparator = new Comparator<MenuTree>() {
            @Override
            public int compare(MenuTree o1,MenuTree o2) {
                if(o1.getOrderNum() !=null && o2.getOrderNum() != null){
                    int bigger = o1.getOrderNum().compareTo(o2.getOrderNum());
                    return (!(bigger==0)?bigger:o1.getMenuId().compareTo(o2.getMenuId()));
                }else {
                    return o1.getMenuId().compareTo(o2.getMenuId());
                }
            }
        };

        for (MenuTree child : menuTreeList) {
            for (MenuTree node : menuTreeList) {
                if(child.getParentId() != null && child.getParentId().equals(node.getMenuId())){
                    node.getChildren().add(child);
                }
                Collections.sort(node.getChildren(),menuTreeComparator);
            }
            if(child.getParentId() == null || child.getParentId().equals(Constant.TOP_MENU)){
                rt.add(child);
            }
        }
        Collections.sort(rt,menuTreeComparator);
        return rt;
    }

}
